package misc

import (
	"fmt"
	"net"
	"strconv"
)

const loopbackIpV4 = "127.0.0.1"
const loopbackIpV6 = "::1"

func GetLocalIps(isIp6 bool) (ips []string) {
	addresses, err := net.InterfaceAddrs()
	if err != nil {
		if isIp6 {
			return []string{loopbackIpV6}
		}
		return []string{loopbackIpV4}
	}
	ips = make([]string, 0)
	for _, address := range addresses {
		if ipNet, ok := address.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
			if ipNet.IP.To4() != nil && !isIp6 {
				ips = append(ips, ipNet.IP.String())
			} else if ipNet.IP.To16() != nil && isIp6 {
				ips = append(ips, ipNet.IP.String())
			}
		}
	}
	if len(ips) == 0 {
		if isIp6 {
			return []string{loopbackIpV6}
		}
		return []string{loopbackIpV4}
	}
	return ips
}
func CheckPort(port int) bool {
	l, err := net.Listen("tcp", fmt.Sprintf(":%s", strconv.Itoa(port)))

	if err != nil {
		return false
	}
	defer func(l net.Listener) {
		err := l.Close()
		if err != nil {

		}
	}(l)
	return true
}
